import "./index.css";
import {
  Button,
  Flex,
  Avatar,
  Space,
  Drawer,
  message, Upload,
} from "antd";
import React, { useState, useRef, useEffect, useContext } from "react";
import {
  MenuOutlined,
  CloudSyncOutlined,
  ArrowLeftOutlined,
  ArrowRightOutlined,
  UserOutlined,
  PlusOutlined,
  BarChartOutlined,
  UploadOutlined,
  HomeOutlined,
  ProfileOutlined,
  ProductOutlined,
  FontSizeOutlined,
  BehanceSquareOutlined,
  CloudUploadOutlined,
  EditOutlined,
  FolderOutlined,
  TableOutlined,
  PictureOutlined,
  FormOutlined,
  QuestionCircleOutlined,
  AppstoreOutlined,
  FullscreenOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import Header from "../../components/canvhae";
import Canhb from "../../components/canhb";
import Design from "../../components/canvleft/design/index";
import Soial from "../../components/canvleft/soial/index";
import Characters from "../../components/canvleft/characters/index";
import Brand from "../../components/canvleft/brand/index";
import Uploadt from "../../components/canvleft/Upload/index";
import Project from "../../components/canvleft/project/index";
import Application from "../../components/canvleft/application/index";
import Mapower from "../../components/canvleft/mapower/index";
import Maheader from "../../components/mamain/maheader";
import { ColorContext } from "../../components/mamain/wabjihe/dianjizh";
import { ColorProvider } from "../../components/mamain/wabjihe/dianjizh";




let Canvas = () => {
  const [textInputs, setTextInputs] = useState([]);
  const [titles, setTitles] = useState([]);
  const [titles1, setTitles1] = useState([]);
  const [titles2, setTitles2] = useState([]);
  const hbplusRef = useRef(null); // 假设你在一个函数组件中
const [color,setColor]=useState('white')
  // 处理添加文本框的回调
  const handleAddTextInput = () => {
    // 这里简单地在数组末尾添加了一个空字符串作为占位符
    // 在实际应用中，你可能需要更复杂的逻辑来处理输入框的值
    setTextInputs((prevTextInputs) => [...prevTextInputs, ""]);
  };

  // 处理添加标题的回调
  const handleAddTitle = () => {
    // 生成一个基于当前时间的唯一标题
    const newTitle = `标题 ${new Date().toLocaleTimeString()}`;
    setTitles((prevTitles) => [...prevTitles, newTitle]);
  };

  const subtitle = () => {
    // 生成一个基于当前时间的唯一标题
    const newTitle = `副标题 ${new Date().toLocaleTimeString()}`;
    setTitles1((prevTitles) => [...prevTitles, newTitle]);
  };

  const Maintext = () => {
    // 生成一个基于当前时间的唯一标题
    const newTitle = `添加一小段正文文字`;
    setTitles2((prevTitles) => [...prevTitles, newTitle]);
  };

  const [scale, setScale] = useState("1");
  // 处理进度条变化的事件
  const handleScaleChange = (e) => {
    // 将进度条的值（通常是 0 到 100）转换为缩放比例（例如，0.5 到 2）
    // 这里我们简单地将范围从 1 到 2 映射到进度条的 0% 到 100%
    const newValue = e.target.value / 25 + 1; // 假设我们想要的范围是 0.5 到 2
    setScale(newValue);
  };

  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState("left");
  const showDrawer = () => {
    setOpen(true);
  };
  const buttonWidth = 80;
  const onClose = () => {
    setOpen(false);
  };
  const [currentId, setCurrentId] = useState(1);
  const options = [
    { label: "设计", id: 1, icon: <ProfileOutlined /> },
    { label: "素材", id: 2, icon: <ProductOutlined /> },
    { label: "文字", id: 3, icon: <FontSizeOutlined /> },
    { label: "品牌", id: 4, icon: <BehanceSquareOutlined /> },
    { label: "上传", id: 5, icon: <CloudUploadOutlined /> },
    { label: "画笔", id: 6, icon: <EditOutlined /> },
    { label: "项目", id: 7, icon: <FolderOutlined /> },
    { label: "应用", id: 8, icon: <TableOutlined /> },
    { label: "魔力素材", id: 9, icon: <PictureOutlined /> },
  ];
  const changeId = (id) => {
    setCurrentId(id);
  };
  

  const dropContainerRef = useRef(null);
  // 拖拽
  useEffect(() => {
      // 获取所有可拖动的图片
      const draggableImages = document.querySelectorAll('.draggable-img');
     // 为每个可拖动的图片添加事件监听器
      draggableImages.forEach(img => {
        img.addEventListener('dragstart', function (event) {
          event.dataTransfer.setData('text/plain', img.src);
          img.style.opacity = '0.5';
        });

        img.addEventListener('dragend', function (event) {
          img.style.opacity = '1';
        });
      });

       // 为目标盒子添加拖放事件监听器
      const dropContainer = document.getElementById('hbplus');
      if (dropContainer) {
        dropContainer.addEventListener('dragover', function (event) {
          event.preventDefault(); // 阻止默认处理（默认不允许放置）
        });

        dropContainer.addEventListener('drop', function (event) {
          event.preventDefault(); // 阻止默认处理
         // 获取拖动的数据（这里是图片的src）
          const imgSrc = event.dataTransfer.getData('text/plain');

          const imgBox=document.createElement('div')
          imgBox.style.position = 'relative';

          // 创建一个新的图片元素
          const newImg = document.createElement('img');
          newImg.src = imgSrc;
          newImg.style.width = '100px'; // 根据需要设置
          newImg.style.height = '100px'; // 根据需要设置
          newImg.style.position = 'absolute'; // 设置绝对定位
          //禁止被拖拽
          newImg.draggable = false;
          let isResizing = false;//是否缩放
          let isRotating = false;//是否旋转
          let startSize = { width: 200, height: 200 };//初始值
          let mouseDownPoint = { x: 0, y: 0 };
          let rotationAngle = 0;//旋转角度

          //点击事件
          newImg.addEventListener('click', (event) => {
            newImg.style.border = '5px solid blue'
            const div = document.createElement('div');
            div.style.position = 'absolute'
            div.style.width = '30px'
            div.style.height = '30px'
            div.style.background = 'red'
            div.style.top = '50px'
            div.style.left = '100px'
            div.style.zIndex = '10';

            //鼠标按下事件
            div.addEventListener('mousedown', (redBoxEvent) => {
              isRotating = true;
              mouseDownPoint.x = redBoxEvent.clientX;
              mouseDownPoint.y = redBoxEvent.clientY;
            });
            //鼠标移动事件
            div.addEventListener('mousemove', (redBoxEvent) => {
              if (isRotating) {
                const currentMouseX = redBoxEvent.clientX;
                const currentMouseY = redBoxEvent.clientY;
                const deltaX = currentMouseX - mouseDownPoint.x;
                const deltaY = currentMouseY-mouseDownPoint.y;
                rotationAngle = Math.atan2(deltaY, deltaX) * (180 / Math.PI);
                //拖拽旋转图片
                newImg.style.transform = `rotate(${rotationAngle}deg)`;
              }
            })
            //鼠标抬起事件
            div.addEventListener('mouseup', () => {
              isRotating = false;
            })
            imgBox.appendChild(div);
          })
          newImg.addEventListener('mousedown', (event) => {
            const rect = newImg.getBoundingClientRect();
            const mouseX = event.clientX;
            const mouseY = event.clientY;
            if (mouseX > rect.right - 10 && mouseY < 10) {
              isRotating = true;
              mouseDownPoint.x = mouseX;
              mouseDownPoint.y = mouseY;
            } else if (mouseX > rect.right - 10 && mouseY > rect.bottom - 10) {
              isResizing = true;
              startSize.width = newImg.width;
              startSize.height = newImg.height;
              mouseDownPoint.x = mouseX;
              mouseDownPoint.y = mouseY;
            } else {
              isRotating = false;
              isResizing = false;
            }
          });

          newImg.addEventListener('mousemove', (event) => {
            if (isRotating) {
              newImg.style.transform = `rotate(${rotationAngle}deg)`
            } else if (isResizing) {
              const currentMouseX = event.clientX;
              const currentMouseY = event.clientY;
              const deltaX = currentMouseX - mouseDownPoint.x;
              const deltaY = currentMouseY - mouseDownPoint.y;

              let scaleX = (startSize.width + deltaX) / startSize.width;
              let scaleY = (startSize.height + deltaY) / startSize.height;

              const minScale = 0.5;
              const maxScale = 2;
              scaleX = Math.max(minScale, Math.min(maxScale, scaleX));
              scaleY = Math.max(minScale, Math.min(maxScale, scaleY));
              newImg.width = Math.floor(startSize.width * scaleX);
              newImg.height = Math.floor(startSize.height * scaleY);
            }
          });
          newImg.addEventListener('mouseup', (event) => {
            isRotating = false;
            isResizing = false;
          })
          imgBox.appendChild(newImg);
          const containerRect = dropContainer.getBoundingClientRect()   // 获取鼠标在视口中的位置
          const x = event.clientX - containerRect.left;
          const y = event.clientY - containerRect.top;
          imgBox.style.left = `${x}px`;
          imgBox.style.top = `${y}px`;
           // 可选：根据需要进行位置调整，例如确保图片不超出容器边界
           // 这里简单地将图片放在鼠标释放的位置
          newImg.style.left = `${x}px`;
          newImg.style.top = `${y}px`;
  
    // 创建删除按钮  
    const deleteButton = document.createElement('button');  
    deleteButton.textContent = '删除';  
    deleteButton.style.position = 'absolute';  
deleteButton.style.top = '5px'; // 距离图片顶部5px  
deleteButton.style.right = '5px'; // 距离图片右侧5px  
deleteButton.style.zIndex = '10';  
  
    // 为删除按钮添加点击事件监听器  
    deleteButton.addEventListener('click', function () {  
      imgBox.remove(); // 删除整个包含图片和按钮的div  
    });  
  
    // 将图片和删除按钮添加到imgBox中  
imgBox.appendChild(newImg);  
imgBox.appendChild(deleteButton);  
  
// 设置imgBox的样式（已经设置，确保再次明确）  
imgBox.style.position = 'absolute';  
imgBox.style.left = `${x}px`; // 这里的x和y是鼠标释放的坐标，适用于imgBox  
imgBox.style.top = `${y}px`;  
  
// 设置图片的样式（由于imgBox已经定位，这里只需要设置内部偏移）  
newImg.style.position = 'absolute';  
newImg.style.left = '0px'; // 相对于imgBox的位置  
newImg.style.top = '0px';  
  
// 设置删除按钮的样式（确保它总是位于图片的右上角）  
deleteButton.style.position = 'absolute';  
deleteButton.style.right = '5px'; // 距离imgBox的右边5px  
deleteButton.style.top = '5px'; // 距离imgBox的顶部5px  
  
// 将imgBox添加到目标容器中  
dropContainer.appendChild(imgBox);  
        });
    }
 
}, []);


  const [divs, setDivs] = useState([]);

  // 定义一个函数来处理点击事件，向divs数组中添加一个新元素
  const addDiv = () => {
    // 假设我们只是简单地向数组中添加一个新索引
    setDivs([...divs, divs.length]);
  };
   const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      // 如果当前没有元素处于全屏状态，则请求全屏
      hbplusRef.current.requestFullscreen();
    } else {
      // 如果已有元素处于全屏状态，则退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  };
  return (
    <div className="canbox">
      <header className="header">
       <Header />
      </header>
      <main>
        <div className="left">
          <div className="lefttype">
            {options.map((item) => {
              return (
                <div
                  key={item.id}
                  onClick={() => changeId(item.id)}
                  className={item.id == currentId ? "active" : ""}>
                  <div className="tablt">
                    <span
                      style={{ float: "left", width: "100%", height: "25px" }}>
                      {item.icon}
                    </span>
                    <span
                      style={{ float: "left", width: "100%", height: "34px" }}>
                      {item.label}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="righttype">
            {/* 设计 */}
            <div style={{ display: currentId == 1 ? "block" : "none" }}>
              <Design />
            </div>
            {/* 素材 */}
            <div style={{ display: currentId == 2 ? "block" : "none" }}>
              <Soial />
            </div>
            {/* 文字 */}
            <div style={{ display: currentId == 3 ? "block" : "none" }}>
              <Characters
                onAddTextInput={handleAddTextInput}
                onAddTitle={handleAddTitle}
                subtitle={subtitle}
                Maintext={Maintext}
              />
            </div>
            {/* 品牌 */}
            <div style={{ display: currentId == 4 ? "block" : "none" }}>
              <Brand />
            </div>
            {/* 上传 */}
            <div style={{ display: currentId == 5 ? "block" : "none" }}>
              <Uploadt />
            </div>
            {/* 画笔 */}
            <div style={{ display: currentId == 6 ? "block" : "none" }}></div>
            {/* 项目 */}
            <div style={{ display: currentId == 7 ? "block" : "none" }}>
              <Project />
            </div>
            {/* 应用 */}
            <div style={{ display: currentId == 8 ? "block" : "none" }}>
              <Application />
            </div>
            {/* 魔力素材 */}
            <div style={{ display: currentId == 9 ? "block" : "none" }}>
              <Mapower />
            </div>
          </div>
        </div>
        <div className="right">
          <header className="nbheader">
           
            <Maheader color={color} setColor={setColor}></Maheader>
          </header>
          <main>
            <div className="divmian">
              <div
                id="hbplus"
                ref={hbplusRef}
                // ref={canvasRef}
                style={{
                  width: "300px", // 初始宽度
                  height: "400px", // 初始高度
                 backgroundColor:color, // 背景颜色，仅为了可视化
                  border: "1px solid #ccc",
                  margin: "20px",
                  transition: "transform 0.2s ease", // 平滑过渡效果
                  transform: `scale(${scale})`, // 应用缩放
                  overflow:'hidden'
                }}>
                <div>
                  {textInputs.map((_, index) => (
                    <input
                      key={index}
                      type="text"
                      placeholder="输入文本"
                    />
                  ))}
                  {titles.map((title, index) => (
                    <h2 key={index}>{title}</h2>
                  ))}
                  {titles1.map((title, index) => (
                    <h4 key={index}>{title}</h4>
                  ))}
                  {titles2.map((title, index) => (
                    <p key={index}>{title}</p>
                  ))}
                </div>
              </div>
            </div>
            {divs.map((index, i) => (
 <div className='divmian'>
              <div  
                  id='hbplus'
                   ref={hbplusRef}
        style={{  
          width: '300px', // 初始宽度  
          height: '400px', // 初始高度
          backgroundColor:color, // 背景颜色，仅为了可视化  
          border:'1px solid #ccc',
          margin: '20px',  
          transition: 'transform 0.2s ease', // 平滑过渡效果  
          transform: `scale(${scale})`, // 应用缩放  
          overflow:'hidden'
        }}  
              >  
<div>  
      {textInputs.map((_, index) => (  
        <input key={index} type="text" placeholder="输入文本" />  
      ))}  
      {titles.map((title, index) => (  
        <h2 key={index}>{title}</h2>  
      ))}  
                  {titles1.map((title, index) => (  
        <h4 key={index}>{title}</h4>  
                  ))}
                  {titles2.map((title, index) => (  
        <p key={index}>{title}</p>  
      ))}
    </div> 
        
              </div>  


              

              </div>
                ))}
            <Button type="primary" className='buttontjym'ghost onClick={addDiv}>添加新页面</Button>
          </main>
          <footer>
            <FormOutlined style={{ margin: "10px" }} />
            <span style={{ margin: "5px", fontWeight: "bold" }}>备注</span>
            <QuestionCircleOutlined
              style={{ float: "right", margin: "10px" }}
            />
            <FullscreenOutlined onClick={toggleFullscreen} style={{ float: "right", margin: "10px" }} > {document.fullscreenElement ? '退出全屏' : '全屏'}</FullscreenOutlined>
            <AppstoreOutlined style={{ float: "right", margin: "10px" }} />
            <input
              className="inputt"
              type="range"
              min="1"
              max="100"
              value={Math.floor((scale - 1) * 25)} // 将缩放比例转换回进度条的值
              onChange={handleScaleChange}
              style={{ marginTop: "10px" }}
            />
            <div style={{ float: "right", margin: "0px 10px 5px 5px" }}>
              页面
            </div>
          </footer>
        </div>
      </main>
    </div>
  );
};

export default Canvas;
